import create from 'zustand'
import { IPermission, ISelectItem, IVrsListModel, IVirtualMeetingRoom } from './interface'
import { subscribeWithSelector } from 'zustand/middleware'
import { fetchGetAllServers } from '@/api/manager/mccMtVideo'
import Alert from '@/components/Alert'
import { fetchCheckVirtualRoomNameExisted, fetchSaveVirtualRoom } from '@/api/sysConfig/virtualRoomConfig'
import { fetchStatus } from '@/api/global'
import { transSaveParams } from './translator'
import { checkRule } from './rules'
import { t } from 'i18next'
import { useGlobalStore } from '@/store/global'
import { checkPermission } from '@/utils'
import { checkSelfMediaValueInList, resetBitrateType, setSelfMediaAbilityList } from './store.media'

export interface VirtualRoomStore {
	isEdit: boolean
	data: IVirtualMeetingRoom
	permission: IPermission
	/** 录播服务器 */
	_vrsServersList: IVrsListModel[]
	_meetingTypeList: ISelectItem[]
	_errorMsg: string
}

type IStore = VirtualRoomStore & {
	update: (d: Partial<VirtualRoomStore>) => void
	reset: () => void
	updateData: (d: Partial<IVirtualMeetingRoom>) => void
	changeMeetingType: (val: 0 | 1 | 2) => void
	changeH265: (val: boolean) => void
	changeRtc: (val: 0 | 1) => void
	changeEncryptionType: (val: 0 | 2 | 3) => void
	changeCallMode: (val: 0 | 2) => void
	resetMeetingProtocol: () => void
	initMeetingTypeList: () => number
	initVrsList: () => Promise<string | undefined>
	saveData: () => Promise<void>
}

export const defaultTpl: IVirtualMeetingRoom = {
	//默认模板
	audioFormats: [],
	allowAnonymousMt: 0,
	autoImageComposition: (window as any).isWeibo ? 1 : 0,
	banMtCancelMute: 0,
	callInterval: '20',
	callMode: 2,
	callTimes: '',
	callTimesUnlimited: true,
	cascadeReturn: false,
	cascadeReturnPara: '',
	cascadeUpload: true,
	dcsMode: 1,
	doubleFlowLimit: 1,
	e164: '',
	enableDCS: false,
	enableLive: false,
	enableRtc: 0,
	enableVideo: false,
	encryptedAuth: false,
	encryptedKey: '',
	encryptedSM: false,
	encryptionType: 0,
	exclusive: false,
	exclusiveUser: [],
	fecMode: 0,
	id: '',
	inExclusive: false,
	initMute: false,
	intelligentRemix: false,
	liveNoLogin: false,
	livePassword: '',
	frame: 30,
	rate: 2048,
	resolution: 12,
	video: 4,
	meetingProtocol: 0,
	meetingType: 1,
	multiStream: false,
	muteException: true,
	nMinusOneMode: 0,
	name: '',
	oneReforming: false,
	password: '',
	publicMeeting: false,
	quantumEncryption: 0,
	simpleCascade: 1,
	sourceUsed: 1,
	startDoubleflow: false,
	status: 0,
	superMtNum: 0,
	type: {
		multi: 192,
		name: t('192方'),
	},
	userDomainMoid: '',
	videoDoubleflow: 1,
	videoPublish: 0,
	videoQuality: 0,
	visible: false,
	visibleUserDomains: [],
	vmrE164: '',
	vmrMoid: '',
	voiceInspireEnable: false,
	voiceInspireTime: 3,
	vrsId: '',
	vrsServerMoid: '',
	watermark: false,
	_H265: false,
	_bitrateType: 3,

	_selfMediaList: [],
	_selfMediaValue: 0,
}

const initialState: VirtualRoomStore = {
	isEdit: false,
	data: defaultTpl,
	permission: {
		tradMix: 0,
		portMix: 0,
		enableVRS: false,
		enableDCS: false,
		enableLive: false,
		enableVideo: false,
		enableQuantum: false,
		enablePortMedia: false,
		enableSfu: false,
		enableTrans: false,
		enableHDMeeting: false,
		certificate: false,
		integrated: false,
		hasAuthenticationServer: false,
		sm1: false,
		'60fps': false,
		'4K': false,
		h265: false,
		has60FpsInH265: false,
	},
	_vrsServersList: [],
	_meetingTypeList: [],
	_errorMsg: '',
}

export const useVirtualRoomStore = create<IStore>()(
	subscribeWithSelector((set, get) => ({
		...initialState,
		update: (d) => set({ ...d }),
		reset: () => set(initialState),
		updateData: (d) => {
			const { data } = get()
			let _data = { ...data, ...d }
			set({ data: _data })
		},
		changeMeetingType: (val) => {
			const { permission, updateData, changeRtc } = get()
			updateData({
				meetingType: val,
				nMinusOneMode: 0,
			})
			resetBitrateType()
			if ((val === 0 && permission.tradMix === 2) || (val === 1 && permission.portMix === 2) || val === 2) {
				changeRtc(1)
			} else {
				changeRtc(0)
			}
		},
		changeRtc: (val) => {
			const { updateData, permission, data, changeH265, changeEncryptionType } = get()
			if (val) {
				updateData({
					voiceInspireEnable: true,
					voiceInspireTime: 3,
					enableRtc: val,
					sourceUsed: permission.integrated ? 1 : 0,
				})
				changeH265(false)
			} else {
				updateData({
					voiceInspireEnable: false,
					voiceInspireTime: 3,
					enableRtc: val,
					sourceUsed: permission.integrated ? 1 : 0,
				})
			}
			if (data._bitrateType === 0) {
				setSelfMediaAbilityList(data.rate) //修改下拉列表数据
				checkSelfMediaValueInList()
			}
			if (data.meetingType === 2) {
				changeEncryptionType(2)
			} else {
				changeEncryptionType(0)
			}
		},
		changeH265(val: boolean) {
			const { _bitrateType, _H265, rate } = useVirtualRoomStore.getState().data
			if (val === _H265) return
			const { updateData } = get()
			updateData({
				_H265: val,
				video: val ? 6 : 4,
			})
			if (_bitrateType !== 0) {
				resetBitrateType()
			} else {
				setSelfMediaAbilityList(rate) //修改下拉列表数据
				checkSelfMediaValueInList()
			}
		},
		changeEncryptionType: (val) => {
			const { updateData, resetMeetingProtocol } = get()
			updateData({
				encryptionType: val,
				encryptedSM: false,
				encryptedAuth: false,
				encryptedKey: '',
				quantumEncryption: 0,
			})
			resetMeetingProtocol()
		},
		changeCallMode: (val) => {
			const { updateData } = get()
			updateData({
				callMode: val,
				callInterval: '20',
				callTimes: '',
				callTimesUnlimited: val === 2 ? true : false,
			})
		},
		//切换时恢复默认值
		resetMeetingProtocol: () => {
			const { data, updateData } = get()
			updateData({
				meetingProtocol: data.enableRtc && !data._H265 && data.encryptionType !== 3 ? 2 : 1,
			})
		},
		//初始化会议类型
		initMeetingTypeList: () => {
			let meetingTypeList = []
			let defaultMeetingType = 0
			const SWITCH = useGlobalStore.getState().SWITCH
			const { permission, update } = get()
			if (permission.enableTrans && checkPermission('100', SWITCH.create.meetingType)) {
				defaultMeetingType = 0 //默认传统
				meetingTypeList.push({ label: t('传统会议'), value: 0 })
			}
			if (permission.enablePortMedia && checkPermission('010', SWITCH.create.meetingType)) {
				defaultMeetingType = 1 //默认端口
				meetingTypeList.push({ label: t('端口会议'), value: 1 })
			}

			if (permission.enableSfu && checkPermission('001', SWITCH.create.meetingType)) {
				defaultMeetingType = defaultMeetingType === 1 ? 1 : 2 //默认sfu
				meetingTypeList.push({ label: t('超元RTC会议'), value: 2 })
			}
			meetingTypeList = meetingTypeList.length === 0 ? [{ label: t('传统会议'), value: 0 }] : meetingTypeList
			update({ _meetingTypeList: meetingTypeList })
			return defaultMeetingType
		},
		//初始录播服务器列表
		initVrsList: async () => {
			const { update } = get()
			let list = await fetchGetAllServers()
			update({
				_vrsServersList: list.map((item) => {
					return {
						netWorkName: item.network_name,
						serverMoid: item.vrs_id,
						serverName: item.server_name,
						serverType: item.server_type,
						value: item.vrs_id,
						label: item.server_name,
					}
				}),
			})
			if (list.length === 1) {
				return list[0].vrs_id
			}
		},
		saveData: async () => {
			const { data, permission, _vrsServersList, reset, updateData } = get()
			// if (state.type?.configCount >= state.type?.totalCount) {
			// 	Alert('所选会议室类型已配置满')
			// }
			if (data.exclusive && !data.exclusiveUser.length) {
				Alert(t('开启专属会议必须添加专属人员'))
			} else if (data.visible && !data.visibleUserDomains.length) {
				Alert(t('开启可见性设置必须添加可见用户域'))
			} else if (
				!(data.encryptionType === 3 && data.encryptedSM) &&
				(permission.enableVideo || permission.enableLive) &&
				permission.enableVRS &&
				!_vrsServersList.length
			) {
				Alert(t('录播服务器故障，请联系管理员'))
			} else if (
				!(data.encryptionType === 3 && data.encryptedSM) &&
				(permission.enableVideo || permission.enableLive) &&
				permission.enableVRS &&
				!data.vrsId
			) {
				Alert(t('请选择录播服务器'))
			} else if (!data.name.trim()) {
				Alert(t('会议室名称不能为空'))
			} else {
				if (!checkRule(data)) {
					return
				}

				let res = await fetchCheckVirtualRoomNameExisted(data.name, data.vmrMoid)
				if (res) {
					Alert(t('会议室名称已存在'))
					return
				}
				if (!/^[\u4e00-\u9fa5A-Za-z0-9]/.test(data.name) || !/[\u4e00-\u9fa5A-Za-z0-9]$/.test(data.name)) {
					Alert(t('首尾字符仅允许输入：英文、数字、汉字'))
					return
				}

				let _data = transSaveParams(data)
				fetchStatus(() => {
					fetchSaveVirtualRoom(_data).then((res) => {
						if (!res.success) {
							Alert(res.description || '')
						} else {
							reset()
						}
					})
				})
			}
		},
	}))
)
